package com.childenglish.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * 邮件服务类
 * 用于发送找回密码验证码等邮件
 */
@Service
public class EmailService {

    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    @Autowired(required = false)
    private JavaMailSender mailSender;

    @Value("${spring.mail.from:noreply@childenglish.com}")
    private String fromEmail;
    
    @Value("${spring.mail.username:}")
    private String mailUsername;
    
    @Value("${spring.mail.password:}")
    private String mailPassword;

    @Value("${app.name:儿童英语学习平台}")
    private String appName;

    /**
     * 发送找回密码验证码
     * @param toEmail 收件人邮箱
     * @param username 用户名
     * @param resetCode 重置验证码
     * @return 是否发送成功
     */
    public boolean sendPasswordResetCode(String toEmail, String username, String resetCode) {
        // 记录邮件配置信息（不记录密码）
        logger.info("邮件服务配置检查 - 发件人: {}, 用户名: {}, 密码是否设置: {}", 
            fromEmail, mailUsername, (mailPassword != null && !mailPassword.isEmpty() ? "是" : "否"));
        
        if (mailSender == null) {
            // 如果邮件服务未配置，输出到控制台
            logger.warn("邮件服务未配置（JavaMailSender bean 未找到），验证码输出到控制台");
            logger.warn("请检查：1. 是否配置了 spring.mail.* 属性；2. 是否添加了 spring-boot-starter-mail 依赖");
            logger.warn("当前邮件配置 - 用户名: {}, 密码: {}", 
                (mailUsername != null && !mailUsername.isEmpty() ? mailUsername : "未设置"),
                (mailPassword != null && !mailPassword.isEmpty() ? "已设置" : "未设置"));
            System.out.println("========================================");
            System.out.println("找回密码验证码（邮件服务未配置）");
            System.out.println("收件人: " + toEmail);
            System.out.println("用户: " + username);
            System.out.println("验证码: " + resetCode);
            System.out.println("有效期: 10分钟");
            System.out.println("========================================");
            return true; // 返回true表示"已发送"（实际是输出到控制台）
        }

        try {
            logger.info("准备发送找回密码验证码邮件到: {}, 发件人: {}", toEmail, fromEmail);
            
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");

            helper.setFrom(fromEmail, appName);
            helper.setTo(toEmail);
            helper.setSubject("找回密码验证码 - " + appName);

            // 构建HTML邮件内容
            String htmlContent = buildPasswordResetEmailHtml(username, resetCode);
            helper.setText(htmlContent, true);

            mailSender.send(message);
            logger.info("找回密码验证码邮件已成功发送到: {}", toEmail);
            return true;
        } catch (MessagingException e) {
            logger.error("发送找回密码验证码邮件失败（MessagingException）: {}", e.getMessage(), e);
            logger.error("请检查：1. 邮箱配置是否正确（spring.mail.host, port, username, password）");
            logger.error("2. QQ邮箱授权码是否正确（不是QQ密码）");
            logger.error("3. 是否开启了QQ邮箱的SMTP服务");
            // 发送失败时也输出到控制台
            System.out.println("========================================");
            System.out.println("找回密码验证码（邮件发送失败，输出到控制台）");
            System.out.println("收件人: " + toEmail);
            System.out.println("用户: " + username);
            System.out.println("验证码: " + resetCode);
            System.out.println("有效期: 10分钟");
            System.out.println("错误: " + e.getMessage());
            if (e.getCause() != null) {
                System.out.println("原因: " + e.getCause().getMessage());
            }
            System.out.println("========================================");
            return false;
        } catch (Exception e) {
            logger.error("发送邮件时发生未知异常: {}", e.getMessage(), e);
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 构建找回密码邮件HTML内容
     */
    private String buildPasswordResetEmailHtml(String username, String resetCode) {
        return "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                "<meta charset='UTF-8'>" +
                "<style>" +
                "body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }" +
                ".container { max-width: 600px; margin: 0 auto; padding: 20px; }" +
                ".header { background: #3498db; color: white; padding: 20px; text-align: center; border-radius: 5px 5px 0 0; }" +
                ".content { background: #f9f9f9; padding: 30px; border-radius: 0 0 5px 5px; }" +
                ".code-box { background: #fff; border: 2px dashed #3498db; padding: 20px; text-align: center; margin: 20px 0; border-radius: 5px; }" +
                ".code { font-size: 32px; font-weight: bold; color: #3498db; letter-spacing: 5px; }" +
                ".warning { color: #e74c3c; font-size: 14px; margin-top: 20px; }" +
                ".footer { text-align: center; margin-top: 30px; color: #7f8c8d; font-size: 12px; }" +
                "</style>" +
                "</head>" +
                "<body>" +
                "<div class='container'>" +
                "<div class='header'>" +
                "<h2>" + appName + "</h2>" +
                "</div>" +
                "<div class='content'>" +
                "<p>尊敬的 <strong>" + username + "</strong>，</p>" +
                "<p>您正在找回密码，请使用以下验证码完成密码重置：</p>" +
                "<div class='code-box'>" +
                "<div class='code'>" + resetCode + "</div>" +
                "</div>" +
                "<p>验证码有效期为 <strong>10分钟</strong>，请及时使用。</p>" +
                "<p class='warning'>⚠️ 如果您没有申请找回密码，请忽略此邮件。</p>" +
                "<div class='footer'>" +
                "<p>此邮件由系统自动发送，请勿回复。</p>" +
                "<p>&copy; " + appName + "</p>" +
                "</div>" +
                "</div>" +
                "</div>" +
                "</body>" +
                "</html>";
    }
}

